using FluentValidation;
using FluentValidation.AspNetCore;
using MediatR;
using Microsoft.AspNetCore.DataProtection.XmlEncryption;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
using System.Reflection;
using WebCoreAPI.Config;
using WebCoreAPI.Filter;
using WebCoreAPI.FluentValidation;
using WebCoreAPI.Identity;
using WebCoreAPI.Models;
using WebCoreAPI.SignalR;
using WebCoreAPI.托管服务;
using Zack.Commons;

namespace WebCoreAPI
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

             //添加跨域访问 CORS
            String[] urls = {"http://localhost:3000"};
            builder.Services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder => builder.WithOrigins(urls)
                .AllowAnyMethod().AllowAnyHeader().AllowCredentials());
            });

            builder.Services.AddControllers();
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            builder.Services.AddSignalR();  //注册SignalR
           

            //builder.Services.AddSingleton<IService,Service>(); //服务注册
            //builder.Services.RunModuleInitializers(ReflectionHelper.GetAllReferencedAssemblies());

            builder.Services.AddMemoryCache(); //内存缓存注册
            //读取机密的配置文件信息
            String redisPWD = builder.Configuration.GetSection("redisPassword").Value;

            //添加Redis的连接
            builder.Services.AddStackExchangeRedisCache(opt =>
            {
                opt.Configuration = "82.157.168.172:6379";
                opt.ConfigurationOptions = ConfigurationOptions.Parse(opt.Configuration);
                opt.ConfigurationOptions.Password = redisPWD;
                opt.ConfigurationOptions.DefaultDatabase = 0;
                opt.InstanceName = "WebCoreAPI_";  //键的前缀
            });


            string? mySqlConStr = "server=82.157.168.172;database=IdentityDemo;uid=feng;pwd=123456Feng!;charset=utf8;";
            builder.Services.AddDbContext<DbContext>(d=>{
                d.UseMySql(mySqlConStr, ServerVersion.AutoDetect(mySqlConStr))
                  .EnableDetailedErrors().EnableSensitiveDataLogging();
            });

          
          

            //注册Filter
            builder.Services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add<SelfExceptionFilter>();  //注册的顺序也影响执行的顺序
                options.Filters.Add<SelfActionFilter>();
                options.Filters.Add<JWTCheckFilter>();
            });

            IdentityInjectConfig.InjectConfig(builder);  //注册Identity
            JWTConfig.InjectConfig(builder);  //注册JWT
            SwaggerConfig.InjectConfig(builder);  //修改Swagger的信息

            builder.Services.AddHostedService<MyBackgroundService>(); //注册托管服务-- 也就是后台服务


            //注册FluentValidation,虽然方法过时，但还能用
            builder.Services.AddFluentValidation(fv => { fv.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());});

            //注册MediatR -事件处理的中间件
            builder.Services.AddMediatR(Assembly.GetExecutingAssembly());

           

            var app = builder.Build();

            app.UseCors();
            app.UseHttpsRedirection();
            if (app.Environment.IsDevelopment()) // 这里就是通过环境变量进行设置的
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            Console.WriteLine("是否为开以环境：" + app.Environment.IsDevelopment());
            Console.WriteLine("是否为测试环境：" + app.Environment.IsStaging());
            Console.WriteLine("是否为正式环境：" + app.Environment.IsProduction());

            app.UseAuthentication(); //添加JWT验证
            app.UseAuthorization();

            app.UseResponseCaching(); //添加服务器端缓存
           
            app.MapHub<MyHub>("/Hubs/ChatRoomHub");  //启用Hub，并给出Hub地址
            
            app.MapControllers();
            app.Run();
        }
    }
}